<script setup>
import { ref, reactive, getCurrentInstance, nextTick ,onMounted } from "vue"
import request from "@/utils/request.js";
import router from "@/router/router.js";
import axios from "axios";
import {ElMessage} from "element-plus";
const { proxy } = getCurrentInstance();


const user=ref(JSON.parse(localStorage.getItem('user') || '{}'))
const circleUrl=ref(user.value.avatar)

// 在页面加载后执行的函数
const init = () => {

  console.log("当前是"+user.value.nickName)
  console.log("刷新了页面");
  //会导致直接跳转
  if (type.value === 1) {
    router.push("/mainAll");
  }
  else if (type.value === 2) {
    router.push("/shareList");
  }
  else if (type.value === 3) {
    router.push("/recycle");
  }
  else if (type.value === 4) {
    router.push("/im");
  }
  getUseState1()
};

// 使用 onMounted 确保页面加载完成后再执行 init
onMounted(() => {
  init();
});

//自动隐藏
const type=ref()
const typeOp=ref()

const op1=()=>{
  console.log("类型转换到1")
  type.value=1;
  typeOp.value=11
  init()
}
const op2=()=>{
  console.log("类型转换到2")
  type.value=2;
  typeOp.value=11
  init()
}
const op3=()=>{
  console.log("类型转换到3")
  type.value=3;
  typeOp.value=11
  init()

}
const op4=()=>{
  console.log("类型转换到4")
  type.value=4;
  typeOp.value=11
  init()

}


const percentage=ref()

// 计算空间占用
const getUseState = async () => {
  try {
    const resp = await axios.post("http://localhost:9090/redis/a");
    // 这里的 response 是 axios 请求返回的响应对象
    const res = resp.data;

    //计算用户使用的空间（MB）
    let UseSpace=res.data;

    // 设置用户初始空间为 5G，换算成 MB
    const totalSpace = 5 * 1024;

    // 从 res.data 中提取实际的数字部分
    const match = res.data.match(/\d+\.?\d*/);
    if (match) {
      const usedSpace = parseFloat(match[0]);

      // 设置用户初始空间为 5G，换算成 MB
      const totalSpace = 5 * 1024;


      percentage.value = Math.round( (usedSpace / totalSpace) * 100);

      console.log(percentage.value);
      ElMessage.success("用户空间更新成功")

    }



  } catch (error) {
    // 处理请求失败的情况
    console.error('请求出错:', error);
  }
};

// 计算空间占用
const getUseState1 = async () => {
  try {
    const resp = await axios.post("http://localhost:9090/redis/a");
    // 这里的 response 是 axios 请求返回的响应对象
    const res = resp.data;

    //计算用户使用的空间（MB）
    let UseSpace=res.data;

    // 设置用户初始空间为 5G，换算成 MB
    const totalSpace = 5 * 1024;

    // 从 res.data 中提取实际的数字部分
    const match = res.data.match(/\d+\.?\d*/);
    if (match) {
      const usedSpace = parseFloat(match[0]);

      // 设置用户初始空间为 5G，换算成 MB
      const totalSpace = 5 * 1024;


      percentage.value = Math.round( (usedSpace / totalSpace) * 100);

      console.log(percentage.value);

    }



  } catch (error) {
    // 处理请求失败的情况
    console.error('请求出错:', error);
  }
};


//退出
const logout=()=>{
  localStorage.removeItem('user');
  router.push("/login")

}


//头像修改处理
const avatarUser=ref({});

const avatarView=ref(false);
const openAvatar=()=>{
  avatarView.value=!avatarView.value;
}
const handleAvatarSuccess= (
    response,
    uploadFile
) => {
  let avatarurl=response.data;
  avatarUser.value.avatar=avatarurl;
  avatarUser.value.userId=user.value.userId;
  console.log(avatarUser.value)
  request.post('/updateAvatar',avatarUser.value).then((res)=>{
    console.log(avatarUser.value)
    if(res.code=='200')
    {
      circleUrl.value=avatarurl;
      avatarView.value=!avatarView.value;
      ElMessage.success('头像更新成功')
      init()


    }
    else
    {
      ElMessage.error('头像更新失败')
    }
  })


}

//个人信息修改
const detailView=ref(false)
const openDetail=()=>{
  detailView.value=!detailView.value
}

const form = ref({
  nickName:user.value.nickName,
  email:user.value.email,
  password:user.value.password,
});

const rules = {
  userId: [{ required: true, message: "请输入用户名",trigger: 'blur' }],
  password: [{ required: true, message: "请输入密码",trigger: 'blur' }],
};

const onSubmit=()=>{
  form.value.userId=user.value.userId;
  console.log(form.value)
  request.post('/updateDetail',form.value).then((res)=>{
    if(res.code=='200')
    {
      user.value.nickName=form.value.nickName
      detailView.value=!detailView.value
      init()
      ElMessage.success('个人信息成功')
    }
    else
    {
      ElMessage.error('更新失败')
    }
  })
}



</script>

<template>
  <div class="framework">
    <div class="header">
      <div class="logo">
        <img class="icon-pan"  src="../assets/wangpan.png"><img>
        <span class="name">智享云盘</span>
      </div>
      <div class="right-panel">
        <el-popover
            :width="800"
            trigger="click"
            :v-model:visible="true"
            :offset="20"
            transition="none"
            :hide-after="0"
            :popper-style="{ padding: '0px' }"
        >
          <template #reference>
            <el-icon size="large" style="cursor: pointer;"><Switch /></el-icon>
          </template>
          <template #default>
            文件上传区域
          </template>
        </el-popover>

        <el-dropdown>
          <div class="user-info">
            <div class="avatar">
              <el-avatar :size="40" :src="circleUrl" />
            </div>
            <span class="nick-name">{{user.nickName}}</span>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="openAvatar">
                修改头像
              </el-dropdown-item>
              <el-dropdown-item @click="openDetail">
                修改个人信息
              </el-dropdown-item>
              <el-dropdown-item @click="logout">
                退出
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="body">
      <div class="left-sider" >
        <div class="menu-list" >
          <div class="menu-item" @click="op1" :class="{ active: type === 1 }">
            <img class="iconfont" src="@/assets/main/main.png" style="height: 30px;width: 30px"> </img>
            <div class="text">首页</div>
          </div>
          <div class="menu-item" @click="op2" :class="{ active: type === 2 }">
            <img class="iconfont" src="@/assets/share/share.png" style="height: 30px;width: 30px"> </img>
            <div class="text">分享</div>
          </div>
          <div class="menu-item" @click="op3" :class="{ active: type === 3 }">
            <img class="iconfont" src="@/assets/back/back.png" style="height: 30px;width: 30px"> </img>
            <div class="text">回收站</div>
          </div>
          <div class="menu-item" @click="op4" :class="{ active: type === 4 }">
            <img class="iconfont" src="@/assets/dialog.png" style="height: 30px;width: 30px"> </img>
            <div class="text">聊天室</div>
          </div>

          <div style="width: 70px ;height: 70px;margin-top: 170px;">
            <div style="text-align: center; font-family: SimSun;">空间占用</div>
            <el-progress class="menu-item"
                :percentage=percentage
                :stroke-width="20"
                         :text-inside="true"
                striped
            />
            <el-button circle size="small" style="margin-top: -10px;margin-left: 25px" @click="getUseState">
              <el-icon><RefreshLeft /></el-icon>
            </el-button>
          </div>
        </div>


          <el-menu router active-text-color="#46B0DB" class="menu-sub-list" v-if="type==1">
            <el-menu-item class="menu-item-sub" index="/mainAll">
              <el-icon class="iconfont"><Grid /></el-icon>
              <span slot="title">全部</span>
            </el-menu-item>
            <el-menu-item class="menu-item-sub" index="/mainVideo">
              <el-icon class="iconfont"><VideoPlay /></el-icon>
              <span slot="title">视频</span>
            </el-menu-item>
            <el-menu-item class="menu-item-sub" index="/mainWord">
              <el-icon class="iconfont"><Document /></el-icon>
              <span slot="title">文档</span>
            </el-menu-item>
<!--            <el-menu-item class="menu-item-sub" index="/im">-->
<!--              <el-icon class="iconfont"><MoreFilled /></el-icon>-->
<!--              <span slot="title">聊天室</span>-->
<!--            </el-menu-item>-->
          </el-menu>

        <el-menu router active-text-color="#46B0DB" class="menu-sub-list" v-if="type==2">
          <el-menu-item class="menu-item-sub" index="/shareList">
            <el-icon class="iconfont"><Grid /></el-icon>
            <span slot="title">分享记录</span>
          </el-menu-item>
          <el-menu-item class="menu-item-sub" index="/shareFind">
            <el-icon class="iconfont"><MoreFilled /></el-icon>
            <span slot="title">获取链接文件</span>
          </el-menu-item>
        </el-menu>


        <el-menu router active-text-color="#46B0DB" class="menu-sub-list" v-if="type==3">
          <el-menu-item class="menu-item-sub" index="/recycle">
            <el-icon class="iconfont"><Grid /></el-icon>
            <span slot="title">回收站</span>
          </el-menu-item>
        </el-menu>
      </div>
      <div class="body-content">
        <router-view v-slot="{ Component }">
          <component
              :is="Component"
          />
        </router-view>
      </div>
    </div>


  </div>

  <el-dialog v-model="avatarView" :show-close="true">
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">头像修改</h4>
      </div>
    </template>
    <el-upload
        class="avatar-uploader"
        action="http://localhost:9090/avatar/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
    >
      <el-icon class="avatar-uploader-icon" style="font-size: 100px;margin-top: 20px;margin-left: 300px"><Plus /></el-icon>
    </el-upload>
  </el-dialog>

  <el-dialog v-model="detailView" :show-close="true">
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">个人信息修改</h4>
      </div>
    </template>

    <el-form
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.prevent
    >
      <!-- input 输入 -->
      <el-form-item label="昵称">
        <el-input
          clearable
          placeholder="请输入信息"
          v-model="form.nickName"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input
            clearable
            placeholder="请输入信息"
            v-model="form.email"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input
            clearable
            placeholder="请输入信息"
            v-model="form.password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>

    </el-form>

  </el-dialog>


</template>

<style lang="scss" scoped>
.header {
  box-shadow: 0 3px 10px 0 rgb(0 0 0 / 6%);
  height: 56px;
  padding-left: 24px;
  padding-right: 24px;
  position: relative;
  z-index: 200;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .logo {
    display: flex;
    align-items: center;
    .icon-pan {
      font-size: 40px;
      color: #1296db;
      height: 50px;
    }
    .name {
      font-weight: bold;
      margin-left: 10px;
      font-size: 25px;
      color: #05a1f5;
    }
  }
  .right-panel {
    display: flex;
    align-items: center;
    .icon-transfer {
      cursor: pointer;
    }
    .user-info {
      margin-right: 10px;
      display: flex;
      align-items: center;
      cursor: pointer;
      .avatar {
        margin: 0px 5px 0px 15px;
      }
      .nick-name {
        color: #05a1f5;
      }
    }
  }
}
.body {
  display: flex;
  .left-sider {
    border-right: 1px solid #f1f2f4;
    display: flex;
    .menu-list {
      height: calc(100vh - 56px);
      width: 80px;
      box-shadow: 0 3px 10px 0 rgb(0 0 0 / 6%);
      border-right: 1px solid #f1f2f4;
      .menu-item {
        text-align: center;
        font-size: 14px;
        font-weight: bold;
        padding: 20px 0px;
        cursor: pointer;
        &:hover {
          background: #f3f3f3;
        }
        .iconfont {
          font-weight: normal;
          font-size: 28px;
        }
      }
      .active {
        background-color: #cbd9f3;
        .iconfont {
          color: #06a7ff;
        }
        .text {
          color: #06a7ff;
        }
      }
    }
    .menu-sub-list {
      width: 200px;
      padding: 20px 10px 0px;
      position: relative;
      .menu-item-sub {
        text-align: center;
        line-height: 40px;
        border-radius: 5px;
        cursor: pointer;
        &:hover {
          background: #f3f3f3;
        }
        .iconfont {
          font-size: 14px;
          margin-right: 20px;
        }
        .text {
          font-size: 13px;
        }
      }
      .active {
        background: #eef9fe;
        .iconfont {
          color: #007bff;
        }
        .text {
          color: #05a1f5;
        }
      }

      .tips {
        margin-top: 10px;
        color: #888888;
        font-size: 13px;
      }

      .space-info {
        position: absolute;
        bottom: 10px;
        width: 100%;
        padding: 0px 5px;
        .percent {
          padding-right: 10px;
        }
        .space-use {
          margin-top: 5px;
          color: #7e7e7e;
          display: flex;
          justify-content: space-around;
          .use {
            flex: 1;
          }
          .iconfont {
            cursor: pointer;
            margin-right: 20px;
            color: #05a1f5;
          }
        }
      }
    }
  }
  .body-content {
    flex: 1;
    width: 0;
    padding-left: 20px;
  }
}


</style>